const vscode = require("vscode")
const { formatJsonString } = require("./format");

function activate(context) {

	let format = vscode.commands.registerCommand("format", async () => {
		// 获取当前激活窗口
		const editor = vscode.window.activeTextEditor;
		if (editor) {
			// 获取当前页面的所有内容
			const document = editor.document;
			const text = document.getText();

			// 格式化json
			const jsonStr = JSON.stringify(JSON.parse(formatJsonString(text)), null, 2)

			// 获取文本范围
			const start = new vscode.Position(0,0);
			const end = document.lineAt(document.lineCount - 1).range.end;
			const fullRange = new vscode.Range(start, end);
			try {
				// 替换当前窗口的内容
				await editor.edit(editBuilder => {
					editBuilder.replace(fullRange, jsonStr);
				})
			} catch (editError){
					console.error("edit error: ", editError)
			}
			console.log("完成")
			
		} else {
			vscode.window.showInformationMessage("没有打开的文本编辑器")
		}
	
	});

	// 注册自定义命令
	context.subscriptions.push(format)
}

module.exports = {activate}